package com.baizhi.controller;


import com.baizhi.aspect.LogAnnotation;
import com.baizhi.entity.Admin;
import com.baizhi.entity.AdminRole;
import com.baizhi.service.IAdminRoleService;
import com.baizhi.service.IAdminService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author haiyu
 * @since 2021-09-06
 */
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private IAdminService ia;

    @Autowired
    public IAdminRoleService ars;

//    @GetMapping("/login/{username}/{password}")
//    public Admin login(@PathVariable("username")String username, @PathVariable("password")String password, HttpSession session) {
//        System.out.println("username = " + username);
//        QueryWrapper<Admin> qw = new QueryWrapper<>();
//        qw.eq("username",username).eq("password",password);
//        Admin one = ia.getOne(qw);
//        if(one!=null){
//            session.setAttribute("user",one);
//        }
//        return one;
//    }
    @LogAnnotation(content = "查询用户分页信息的操作")
    @GetMapping("/selectAdmin")
    @PreAuthorize("hasAuthority('sys:schedule:list,sys:schedule:info')")
    public IPage<Admin> selectAdmin(Integer pageNo, Integer pageSize, String name){
        Page<Admin> page = new Page<>(pageNo,pageSize);
        QueryWrapper<Admin> wrapper=new QueryWrapper<>();
        if(name!=null&&!"".equals(name)){
            wrapper.eq("username",name);
        }
        IPage<Admin> page1 = ia.page(page, wrapper);
        return page1;

    }
    @PostMapping("/addAmin")
    @PreAuthorize("hasAuthority('sys:schedule:save')")
    public void addAdmin(@RequestBody Admin admin){


        //保存admin对象
        ia.save(admin);
        //保存该用户对应的角色
        Integer adminId = admin.getId();//用户的id值
        List<Integer> roleIds = admin.getRoleIds();//该用户所拥有的角色id值
        //往adminRole表里面存储数据
        for (Integer roleId:roleIds){
            AdminRole ar=new AdminRole();
            ar.setAdminId(adminId);
            ar.setRoleId(roleId);
            ars.save(ar);
        }
    }
    @LogAnnotation
    @GetMapping("/get")
    public Admin select(String name){

        Admin select = ia.select(name);
        return select;
    }

 }
